package com.young;

import com.young.service.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;


//@Configuration用于将一个类变成配置类，相当于xml文件
@Configuration
//@EnableWebSecurity注解开启Spring Security的功能
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter  {

    @Autowired
    private UserDetailService userDetailService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //通过authorizeRequests()定义哪些URL需要被保护、哪些不需要被保护
        http.authorizeRequests()
                //  /和/home不需要任何认证就可以访问
                .antMatchers("/","/home").permitAll()
                // 其他的路径都必须通过身份验证
                .anyRequest().authenticated()
                .and()
                //通过formLogin()定义当需要用户登录时候，转到的登录页面
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .and()
                //访问 /login?logout 可注销登录
                .logout()
                .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        // 在内存中创建了一个用户
        // spring security 5.0 增加了加密方式校验，因此需要提前将用户名和密码加密，否则报错
        // 参考 https://blog.csdn.net/Canon_in_D_Major/article/details/79675033
        /*auth.inMemoryAuthentication()
                .passwordEncoder(new BCryptPasswordEncoder()).withUser("user")
                .password(new BCryptPasswordEncoder().encode("password")).roles("USER");
        */
        // 此处是通过内存中的用户名和密码进行校验，也可自定义校验类，读取数据库用户名和密码来校验
        // 例如 auth.userDetailsService(userDetailService);
        // 参考 https://www.cnblogs.com/scau-chm/p/5967931.html　
        //https://blog.csdn.net/u012373815/article/details/60465776
        //https://gitee.com/shenzhanwang/spring-security-demo/tree/master

        //调用userDetailsService接口进行自定义服务的密码校验
        //由于注册时使用的是BCrypt加密，故验证密码前也要将用户输入的密码加密
        auth.userDetailsService(userDetailService).passwordEncoder(new BCryptPasswordEncoder());
    }

    //用于启用@Secured所必需的
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
